use crate::error::{TauriResult, TauriCommandError, CommandResponse};
use crate::types::{FileItem, WorkspaceInfo, FileOperationResult, FilePermissions};
use crate::services::filesystem::FilesystemService;
use std::path::Path;
use std::fs;
use tauri::command;

/// 打开工作区
#[command]
pub async fn open_workspace(path: String) -> TauriResult<CommandResponse<WorkspaceInfo>> {
    log::info!("Opening workspace: {}", path);
    
    let workspace_path = Path::new(&path);
    if !workspace_path.exists() {
        return Ok(CommandResponse::error("工作区路径不存在"));
    }
    
    if !workspace_path.is_dir() {
        return Ok(CommandResponse::error("指定路径不是目录"));
    }
    
    match FilesystemService::scan_workspace(&path).await {
        Ok(workspace_info) => {
            log::info!("Workspace opened successfully: {} files found", workspace_info.files.len());
            Ok(CommandResponse::success(workspace_info))
        }
        Err(e) => {
            log::error!("Failed to open workspace: {}", e);
            Ok(CommandResponse::error(format!("打开工作区失败: {}", e)))
        }
    }
}

/// 读取文件内容
#[command]
pub async fn read_file(path: String) -> TauriResult<CommandResponse<String>> {
    log::debug!("Reading file: {}", path);
    
    match fs::read_to_string(&path) {
        Ok(content) => {
            log::debug!("File read successfully: {} bytes", content.len());
            Ok(CommandResponse::success(content))
        }
        Err(e) => {
            log::error!("Failed to read file {}: {}", path, e);
            Ok(CommandResponse::error(format!("读取文件失败: {}", e)))
        }
    }
}

/// 写入文件内容
#[command]
pub async fn write_file(path: String, content: String) -> TauriResult<CommandResponse<FileOperationResult>> {
    log::debug!("Writing file: {} ({} bytes)", path, content.len());
    
    match fs::write(&path, &content) {
        Ok(_) => {
            let result = FileOperationResult::success(
                "write".to_string(),
                path,
                "文件保存成功".to_string(),
            );
            log::debug!("File written successfully");
            Ok(CommandResponse::success(result))
        }
        Err(e) => {
            let result = FileOperationResult::error(
                "write".to_string(),
                Some(path),
                format!("写入文件失败: {}", e),
            );
            log::error!("Failed to write file: {}", e);
            Ok(CommandResponse::success(result))
        }
    }
}

/// 监控目录变化
#[command]
pub async fn watch_directory(path: String) -> TauriResult<CommandResponse<String>> {
    log::info!("Starting directory watch: {}", path);
    
    match FilesystemService::start_watching(&path).await {
        Ok(watcher_id) => {
            log::info!("Directory watcher started: {}", watcher_id);
            Ok(CommandResponse::success(watcher_id))
        }
        Err(e) => {
            log::error!("Failed to start directory watcher: {}", e);
            Ok(CommandResponse::error(format!("启动目录监控失败: {}", e)))
        }
    }
}

/// 创建文件
#[command]
pub async fn create_file(path: String) -> TauriResult<CommandResponse<FileOperationResult>> {
    log::debug!("Creating file: {}", path);
    
    let file_path = Path::new(&path);
    
    if file_path.exists() {
        let result = FileOperationResult::error(
            "create_file".to_string(),
            Some(path),
            "文件已存在".to_string(),
        );
        return Ok(CommandResponse::success(result));
    }
    
    // 确保父目录存在
    if let Some(parent) = file_path.parent() {
        if let Err(e) = fs::create_dir_all(parent) {
            let result = FileOperationResult::error(
                "create_file".to_string(),
                Some(path),
                format!("创建父目录失败: {}", e),
            );
            return Ok(CommandResponse::success(result));
        }
    }
    
    match fs::File::create(&path) {
        Ok(_) => {
            let result = FileOperationResult::success(
                "create_file".to_string(),
                path,
                "文件创建成功".to_string(),
            );
            log::debug!("File created successfully");
            Ok(CommandResponse::success(result))
        }
        Err(e) => {
            let result = FileOperationResult::error(
                "create_file".to_string(),
                Some(path),
                format!("创建文件失败: {}", e),
            );
            log::error!("Failed to create file: {}", e);
            Ok(CommandResponse::success(result))
        }
    }
}

/// 创建目录
#[command]
pub async fn create_directory(path: String) -> TauriResult<CommandResponse<FileOperationResult>> {
    log::debug!("Creating directory: {}", path);
    
    match fs::create_dir_all(&path) {
        Ok(_) => {
            let result = FileOperationResult::success(
                "create_directory".to_string(),
                path,
                "目录创建成功".to_string(),
            );
            log::debug!("Directory created successfully");
            Ok(CommandResponse::success(result))
        }
        Err(e) => {
            let result = FileOperationResult::error(
                "create_directory".to_string(),
                Some(path),
                format!("创建目录失败: {}", e),
            );
            log::error!("Failed to create directory: {}", e);
            Ok(CommandResponse::success(result))
        }
    }
}

/// 删除文件或目录
#[command]
pub async fn delete_file_or_directory(path: String) -> TauriResult<CommandResponse<FileOperationResult>> {
    log::debug!("Deleting: {}", path);
    
    let file_path = Path::new(&path);
    
    if !file_path.exists() {
        let result = FileOperationResult::error(
            "delete".to_string(),
            Some(path),
            "文件或目录不存在".to_string(),
        );
        return Ok(CommandResponse::success(result));
    }
    
    let operation_type = if file_path.is_dir() { "delete_directory" } else { "delete_file" };
    
    let result = if file_path.is_dir() {
        fs::remove_dir_all(&path)
    } else {
        fs::remove_file(&path)
    };
    
    match result {
        Ok(_) => {
            let result = FileOperationResult::success(
                operation_type.to_string(),
                path,
                "删除成功".to_string(),
            );
            log::debug!("Deletion successful");
            Ok(CommandResponse::success(result))
        }
        Err(e) => {
            let result = FileOperationResult::error(
                operation_type.to_string(),
                Some(path),
                format!("删除失败: {}", e),
            );
            log::error!("Failed to delete: {}", e);
            Ok(CommandResponse::success(result))
        }
    }
}

/// 重命名文件或目录
#[command]
pub async fn rename_file_or_directory(old_path: String, new_path: String) -> TauriResult<CommandResponse<FileOperationResult>> {
    log::debug!("Renaming: {} -> {}", old_path, new_path);
    
    match fs::rename(&old_path, &new_path) {
        Ok(_) => {
            let result = FileOperationResult::success(
                "rename".to_string(),
                new_path,
                "重命名成功".to_string(),
            );
            log::debug!("Rename successful");
            Ok(CommandResponse::success(result))
        }
        Err(e) => {
            let result = FileOperationResult::error(
                "rename".to_string(),
                Some(old_path),
                format!("重命名失败: {}", e),
            );
            log::error!("Failed to rename: {}", e);
            Ok(CommandResponse::success(result))
        }
    }
}

/// 读取目录内容
#[command]
pub async fn read_directory(path: String) -> TauriResult<CommandResponse<Vec<FileItem>>> {
    log::debug!("Reading directory: {}", path);
    
    match FilesystemService::read_directory(&path).await {
        Ok(items) => {
            log::debug!("Directory read successfully: {} items", items.len());
            Ok(CommandResponse::success(items))
        }
        Err(e) => {
            log::error!("Failed to read directory {}: {}", path, e);
            Ok(CommandResponse::error(format!("读取目录失败: {}", e)))
        }
    }
}
